<template>
  <el-dialog v-model="visible" :title="title" width="50%">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="快递单号" prop="code">
        <el-input v-model="form.code" placeholder="请输入快递单号" />
      </el-form-item>
      <el-form-item label="快递公司" prop="company">
        <el-select-v2
          v-model="form.company"
          :options="expressCompanyStore.list"
          :props="{ value: 'id', label: 'name' }"
          placeholder="请选择快递公司"
        />
      </el-form-item>
      <el-form-item label="源订单" prop="origin">
        <el-input v-model="form.origin" placeholder="请输入源订单" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { useExpressStoreHook } from "@/store/modules/logistics/express";
import { useExpressCompanyStoreHook } from "@/store/modules/logistics/company";
import type { ExpressForm } from "@/api/logistics/express";

const props = defineProps<{
  formData: ExpressForm;
  type: "add" | "edit";
}>();

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "confirm"): void;
}>();

const expressStore = useExpressStoreHook();
const expressCompanyStore = useExpressCompanyStoreHook();

const visible = defineModel<boolean>("modelValue", { required: true });
const formRef = ref();
const form = ref<ExpressForm>({
  ...props.formData,
});

const title = computed(() => {
  return props.type === "add" ? "添加快递单" : "编辑快递单";
});

watch(visible, (val) => {
  if (val) {
    Object.assign(form.value, props.formData);
  } else {
    formRef.value.resetFields();
  }
});

const rules = {
  code: [{ required: true, message: "请输入快递单号", trigger: "blur" }],
  company: [{ required: true, message: "请选择快递公司", trigger: "change" }],
  origin: [{ required: true, message: "请输入源订单", trigger: "blur" }],
};

async function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    if (props.type === "add") {
      await expressStore.fetchCreateExpress(form.value);
    } else {
      console.log(form.value);
      await expressStore.fetchUpdateExpress(form.value);
    }
    emits("confirm");
    visible.value = false;
  });
}

onMounted(async () => {
  expressCompanyStore.fetchList({ page: 1, size: 999999 });
});
</script>

<style scoped lang="scss"></style>
